<?php
namespace app\file\controller;
use app\common\controller\Common;

class File extends Common
{
	protected $msg = [
		'file_empty'		=> '文件为空',
		'file_error'		=> '文件错误',
		'file_min_size'		=> '文件最小，不低于',
		'file_max_size'		=> '文件最大，不超过',
		'file_end'			=> '文件后缀名错误',
		'upload_error'		=> '文件上传失败',
	];
	protected $file = [];//文件数据
	protected $field = 'img';//文件对应字段
	protected $end = '';//文件后缀名
	protected $catalog = '';//保存时文件目录
	protected $filename = '';//保存时文件名字

	public function file_upload()
	{
		$this->valiteFile();
		$this->valiteError();
		$this->valiteMinSize(config('parameter.img_min_size'));
		$this->valiteMaxSize(config('parameter.img_max_size'));
		$this->getEnd();
		$this->valiteEnd(config('parameter.img_end'));
		$this->setCatalog();
		$this->createName();
		$this->moveFile();
	}

	/************************** 私有 *********************/

	/**
	 * 设置文件目录
	 */
	protected function setCatalog()
	{
		$this->catalog = config('parameter.img_catalog'). '/' .date('Ymd',time());
        $dir = iconv("UTF-8","GBK",$this->catalog);
        if (!file_exists($dir)){
            mkdir ($dir,0777,true);
        }
	}
	/**
	 * 保存时的文件名字
	 */
	protected function createName()
	{
		$this->filename = $this->field . md5($this->file['name']) . '.' . $this->end;
	}
	/**
	 * 保存文件
	 */
	protected function moveFile()
	{
		$this->filename = $this->catalog . '/' . $this->filename;
		if( !@move_uploaded_file($this->file["tmp_name"],$this->filename) ){
			$this->error($this->msg['upload_error']);
		}
		$this->success('/' . $this->filename);
	}
	/**
	 * 文件验证
	 */
	protected function valiteFile()
	{
		if(!isset($_FILES['file']) || empty($_FILES['file'])){
			$this->error( $this->msg['file_empty'] );
		}
		$this->file = $_FILES['file'];
		$data = Request()->param('');
		if( isset($data['field']) && $data['field'] != '' ){
			$this->field = $data['field'];
		}
	}
	/**
	 * 文件错误验证
	 */
	protected function valiteError()
	{
		if($this->file['error'] > 0){
			$this->error( $this->msg['file_error'] );
		}
	}
	/**
	 * 文件最小值验证
	 * @param  intger $img_min_size 文件最小值
	 */
	protected function valiteMinSize($img_min_size)
	{
		if($img_min_size != '*' && $img_min_size > $this->file['size']){
			$this->error( $this->msg['file_min_size'].$img_min_size.'b' );
		}
	}
	/**
	 * 文件最大值验证
	 * @param  intger $img_max_size 文件最小值
	 */
	protected function valiteMaxSize($img_max_size)
	{
		if($img_max_size != '*' && $img_max_size < $this->file['size']){
			$this->error( $this->msg['file_max_size'].$img_max_size.'b' );
		}
	}
	/**
	 * 获取后缀名
	 * @return string 后缀名
	 */
	protected function getEnd()
	{
		$arr = explode('.', $this->file['name']);
		$this->end = end($arr);
	}
	/**
	 * 后缀名验证
	 */
	protected function valiteEnd($img_end)
	{
		if($img_end != '*' && !in_array($this->end, $img_end)){
			$this->error($this->msg['file_end']);
		}
	}
}